package com.hm.ruiji.controller;

import com.hm.ruiji.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/*
文件下载上传
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    // 文件存储路径，在配置文件中配置
    @Value("${ruiji.path}")
    private String PATH;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info("上传文件：{}",file.toString());

        // 获取上传文件原文件名
        String originalFilename = file.getOriginalFilename();
        log.info("原文件名：【{}】", originalFilename);

        // 截取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 新文件名
        String fileName = UUID.randomUUID().toString() + suffix;

        File file1 = new File(PATH);

        if (!file1.exists()) file1.mkdirs();
        log.info("转存文件路径：【{}】",PATH+fileName);

        try {
            // 将临时文件转存到指定路径
            file.transferTo(new File(PATH+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     * @return
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        try {
            // 输入流，读取文件内容
            FileInputStream inputStream = new FileInputStream(new File(PATH + name));
            // 输出流，将文件写回浏览器，展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            // 设置响应数据类型为图片
            response.setContentType("image/jpeg");
            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1){
                // 写入读取的文件
                outputStream.write(bytes, 0, len);
                // 刷新

            }
            outputStream.close();
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
